$.ajaxSetup({
  beforeSend: function () {},
  // dataFilter: function (data, type) {
  // },
  complete: function (xhr, status) {
    if (xhr.status == "9981") {

      // mui.toast("当前用户会话过期,将要跳转登录页面!", { duration: 'long', type: 'div' })
      mui.toast("当前用户会话过期,将要自动跳转登录页面!", {
        duration: "long",
        type: "div",
      });
      setTimeout(function () {
        $(location).attr("href", "../index.html");
      }, 1500);
      // alert("当前用户会话过期,将要跳转登录页面!")
      // $(location).attr("href", "../index.html");
    } else if (xhr.status == "200") {
    } else {
    }
  },
});
// document.write("<script type='text/javascript' src='../js/sm3.js'></script>");

// let wxConfig = {
//     appId: "ww445f8033443a14aa", // 必填，政务微信的cropID //开发环境  ww445f8033443a14aa  生产环境 后续给
//     nonceStr: "AMQGnmTMzhJetshY", // 必填，生成签名的随机串
//     signature: "fb9f560a9b4824f7db3525926994010de74ea055" // 必填，签名，见附录1
// }

// let appId = "ww445f8033443a14aa" //开发环境  ww445f8033443a14aa  生产环境 后续给
let nonceStr = "AMQGnmTMzhJetshY"; // 必填，生成签名的随机串
let signature = "fb9f560a9b4824f7db3525926994010de74ea055"; // 必填，签名，见附录1
let urlLocalport = "18083"; //本地port 不管 后续提供
let timestamp = Date.now();
let userId;
let userName;
let unitId;
let urlLinkIp = "61.133.196.129" //交互平台ip  开发iscp 生产 127.0.0.1
var homeKey =
  "df9033616b66f748fae60ee74de1c2640041493566995d4a2217394231ed7a0f";

var iscp = {
  port: "",
};
let iscp_port;
if (sessionStorage.getItem("iscp_port")) {
  iscp_port = sessionStorage.getItem("iscp_port");
} else {
  iscp_port = "";
}

//测试环境
// let corpid = "ww445f8033443a14aa";
// // let agentid = "1002435"; //账户 Isc AppId
// // ！ 修改二
// let isc_appid = "6a31d14b09914eb1bdf94d099954758d"; //账户 Isc AppId
// // let isc_appid = "ae9f706e13a14507b520ff8d839a4ead"; //账户 Isc AppId
// let sURLgetWxCode = "https://igw.isgcc.net:18081/connect/oauth2/authorize?";
// let appid = "ww445f8033443a14aa"; //写死
// let encodeURIComponentUrl = "zipapp://local.host/index.html";
// // ！ 修改一
// let magentid = "1003596";
// // let magentid = "1002872";
// let sURLgetIscToken =
// "https://igw.isgcc.net:18443/identity/getAuthTicketByWechatCode";

// let isFlag = true; //true 开发模式 false 生产
// let isFlagOne = false; //true 脱敏 fasle不托
// var localUrlLink;
// if (isFlag) {
//   localUrlLink = "http://172.23.4.199:80";
// } else {
//   localUrlLink = "http://127.0.0.1:";
// }





// 生产模式 （上线之前需打开此模式，uat环境勿打，相邻//中间代码）
let corpid = "ww4d11a39991ebffdc";
let isc_appid = "9128b269d2e8408babd632ebca95f3f8"; //账户 Isc AppId
let sURLgetWxCode = "https://igw.sgcc.com.cn/connect/oauth2/authorize?"
let appid = "ww4d11a39991ebffdc" //写死
let encodeURIComponentUrl = "zipapp://local.host/index.html"
let magentid = '1001064'
let sURLgetIscToken = "https://id.sgcc.com.cn:10443/ticket/identity/getAuthTicketByWechatCode"
let isFlag = false; //true 开发模式 false 生产 
let isFlagOne = false;//true 脱敏 fasle不托
var localUrlLink = "http://127.0.0.1:"






let urlLocalip = "172.16.3.29"; //本地ip 不管 后续提供
// let urlLocalip = "172.20.8.196"; //本地ip 不管 后续提供
let urlServerappid = "ndypl" //应用id  不管 后续提供
let urlServeruser = "buser"; //用户id  写死 不管
let urlLinkPort = "6001"; //交互平台port   写死 不管
let toMail = ""; //公共邮箱
// let toMail = "3092975049@qq.com"; //公共邮箱

let urlMyLink = urlLinkIp + ":" + urlLinkPort; //链路标识 60.28.54.50:20084
let jsApiList = []; //需要使用的功能接口
let vconsole = new VConsole();
// 隐藏 vConsole 的开关按钮
$(() => {
  let vconsoleFlag = sessionStorage.getItem("vconsoleFlag");
  if (vconsoleFlag != "true") {
    vconsole.hideSwitch();
  }
});

//  开发环境不走 安全交互
function createISCPLink(int) {
  $("#showP").html(" 正在建立安全连接...");
  $.getScript("./js/jweixin-1.2.0.js" /*"js/jweixin-1.0.0.js"*/, function () {
    "use strict";
    wx.ready(function () {});
    jsApiList = [
      "ext_ISCP_Init",
      "ext_ISCP_ConnectService",
      "ext_ISCP_GetLocalPort",
      "ext_ISCP_Close",
      "ext_ISCP_Status",
      "ext_Popover_Open",
      "ext_Popover_Close",
      "multiWindows_open",
      "multiWindows_close",
      "multiWindows_startWidget",
      "multiWindows_finishWidget",
      "multiWindows_subscribe",
      "multiWindows_publish",
      "shareWechatMessage",
      "onMenuShareTimeline",

      "chooseImage",
      "getLocalImgData",
      "previewImage",
      "uploadImage",
      "downloadImage",
      "previewFile",

      "startRecord",
      "stopRecord",
      "onVoiceRecordEnd",
      "playVoice",
      "playVoice",
      "stopVoice",
      "onVoicePlayEnd",
      "startRecordVoiceBuffer",
      "onRecordBufferReceived",
      "stopRecordVoiceBuffer",
      "uploadVoice",
      "downloadVoice",
      "translateVoice",

      "setClipboardData",
      "getClipboardData",

      "openLocation",
      "startAutoLBS",
      "stopAutoLBS",
      "onLocationChange",

      "onHistoryBack",
      "closeWindow",
      "openUrl",

      "scanQRCode",

      "launch3rdApp",

      "ocr",

      "checkJsApi",
    ];
    wx.config({
      beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: appid, // 必填，政务微信的cropID
      timestamp: "1626832073", // 必填，生成签名的时间戳
      nonceStr: nonceStr, // 必填，生成签名的随机串
      signature: signature, // 必填，签名，见附录1
      jsApiList: jsApiList, // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
    login_ready()
    console.log(7777)
    iscpInit(function(){
      // if(!err) {
        console.log(sessionStorage.getItem("auth_data"),"1111")
        sessionStorage.getItem("auth_data") && getAuthentication(sessionStorage.getItem("auth_data"))

      // }
    })
    // 初始化
  });
}
// function login() {
//     var access_token = "";
//     let userId = sessionStorage.getItem("userId");
//     let data = {
//         "userId": userId,
//         "timestamp": new Date().getTime() + "" //时间戳
//     }
//     if (sessionStorage.getItem("iscp_port")) {
//         iscp_port = sessionStorage.getItem("iscp_port");
//     } else {
//         iscp_port = ""
//     }
//     data = JSON.stringify(data)
//     let sign = sm3(data);
//     let AuthenticationSession = sessionStorage.getItem("Authentication");
//     $.ajax({
//         url: localUrlLink + iscp_port + "/pxapi/oauth/getToken",
//         type: "post",
//         async: false, //是否同步，false表示同步请求 true表示异步请求
//         dataType: "json",
//         data: data,
//         headers: {
//             "Content-Type": "application/json;charset=UTF-8",
//             sign: sign,
//             Authentication: AuthenticationSession,
//         },
//         success: (res, txt, xhr) => {
//             if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
//                 let Authentication = xhr.getResponseHeader("Authentication")
//                 if (res.code == 200) {
//                     if (Authentication) {
//                         sessionStorage.setItem("Authentication", Authentication);
//                         access_token = res.resultValue;

//                     }
//                 } else {
//                     $(".curtain").css("display", "none");
//                     mui.toast(res.resultValue, {
//                         duration: 'long',
//                         type: 'div'
//                     })
//                 }
//             } else {
//                 $(".curtain").css("display", "none");
//                 mui.toast('完整性校验失败', {
//                     duration: 'long',
//                     type: 'div'
//                 })
//             }
//         },
//         error: (e) => {
//             $(".curtain").css("display", "none");
//             mui.toast("请求异常请稍后再试", {
//                 duration: 'long',
//                 type: 'div'
//             })
//         },

//     });
//     return access_token;
// };
function utilFunc(map) {
  var sortMap = function (map, isKeyUpSort) {
    let keys = new Array();
    for (var key of map.keys()) {
      keys.push(key);
    }
    if (isKeyUpSort) {
      keys = keys.sort(function (key1, key2) {
        return key1.localeCompare(key2);
      });
    } else {
      keys = keys.sort(function (key1, key2) {
        return key2.localeCompare(key1);
      });
    }
    let str = "";
    keys.forEach((key) => {
      if (null != map.get(key) && "" != map.get(key)) {
        str = str + key + "=" + map.get(key);
      }
    });
    return str;
  };
  var str = sortMap(map, true);
  let hashData = sm3(str);

  let hashData_last = sm3(hashData);
  hashData_last = hashData_last.substr(0, 5);
  hashData += hashData_last;
  return hashData;
}
// 初始化
function iscpInit() {
  wx.invoke(
    "ext_ISCP_Init",
    {
      data: {
        iscpIP: urlMyLink,
      },
    },
    function (res) {
      if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
        // $(".iscp-loading").css({ "display": "none" });
        // $($(".eis-step-icon").data("codeTrig", true).get(0)).click();
        // $(".eis-step-icon").removeData("codeTrig");
        // $("button").removeAttr("disabled");
        // $(".iscp-form").hide();
        // $($(".iscp-form").get(1)).show();
        $("#showP").html("建立安全连接初始化成功");
        iscpConnection();
      } else {
        $("#showP").html("建立安全连接初始化失败");
      }
    }
  );
}
// 建立连接
function iscpConnection() {
  wx.invoke(
    "ext_ISCP_ConnectService",
    {
      data: {
        iscpIP: urlMyLink,
        ip: urlLinkIp,
        port: urlLinkPort,
        user: urlServeruser,
        appid: urlServerappid,
      },
    },
    function (res) {
      if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
        $("#showP").html("建立安全连接成功");
        iscpTransferPort();
      } else {
        $("#showP").html("建立安全连接失败");
      }
    }
  );
}

// 获取端口
function iscpTransferPort() {
  wx.invoke(
    "ext_ISCP_GetLocalPort",
    {
      data: {
        iscpIP: urlMyLink,
        ip: urlLocalip,
        port: urlLocalport,
      },
    },
    function (res) {
      if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
        iscp.port = res.result;
        sessionStorage.setItem("iscp_port", res.result);

        $("#showP").html("建立安全连接获取端口成功");
        // iscpState()  //感觉没用
        sessionStorage.setItem("err_msg", "err_msg");
      } else {
        $("#showP").html("建立安全连接获取端口失败");
      }
    }
  );
}

// 连接状态
function iscpState() {
  wx.invoke(
    "ext_ISCP_Status",
    {
      data: {
        iscpIP: urlMyLink,
      },
    },
    function (res) {
      if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
        if (res.result == "0") {
          console.log("未连接");
        } else if (res.result == "1") {
          console.log("正在连接");
        } else if (res.result == "2") {
          console.log("已连接");
          sessionStorage.setItem("err_msg", "err_msg");
        }
      } else {
        $("#showP").html("建立安全连接失败");
      }
    }
  );
}

// 关闭连接
function closeIscp() {
  wx.invoke(
    "ext_ISCP_Close",
    {
      data: {
        iscpIP: urlMyLink,
      },
    },
    function (res) {
      if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
        // $(".iscp-loading").css({
        //     "display": "none"
        // });
        // $($(".eis-step-icon").data("codeTrig", true).get(5)).click();
        // $(".eis-step-icon").removeData("codeTrig");
        //$("button").removeAttr("disabled");
      }
    }
  );
}

var token =
  "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bml0TmFtZSI6InVuaXROYW1lIiwidXNlck5hbWUiOiJ1c2VyTmFtZSIsImV4cCI6MTYzNzgzMzk4NCwidXNlcklkIjoidXNlcklkIiwiaWF0IjoxNjM3NTc0Nzg0fQ.9eHYxliOGN0x3BiHbo36GpPbw8JOJdUABJ9cvIP-Taw";
/*操作日志异步公共接口  
    operatorType 1/用户登陆 、登出 2/OCR识别 
    operatorBasic  1/打印 2/手写 3/身份证 4/增值税 5/火车票    
    operatorContent 1//复制文本 2/发送邮箱 3/识别
*/

function addOperator(
  type,
  basic,
  content,
  isDel,
  operatorStatus,
  through,
  time
) {
  userId = sessionStorage.getItem("userId");
  // userName = sm2UserName()
  // if (userName == "***") {
  //     alert("userName解密错误")
  //     return
  // }
  // let msgName = userName + "," + sm3(userName)
  // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let data = {
    userId: userId, //用户id
    operator: "", //操作人  现已废弃
    operatorIP: "001", //操作ip
    operatorType: type, //type 1：用户登录注销 2：OCR识别 3：语音识别 4：我的
    operatorBasic: basic, //基于type 1.1：用户登录 1.2：用户注销 2.1：打印文字识别 2.2：手写文字识别 2.3：身份证识别 2.4：增值税专票识别 2.5：火车票识别 2.6：表格识别 2.7：Pdf转word 2.8：银行卡识别 2.9：增值税普票识别 2.10：工作票识别 2.11：操作票识别 2.12：出租车票识别 2.13：航空行程单识别 3.1：现场速记 3.2：语音笔记 3.3：录音转写 4.1：邮箱 4.2：安全知情同意书
    operatorContent: content, //基于type 1：登录、注销 2：识别、复制文本、发送邮箱、发送内网、下载文件 3：完成保存、复制、发送邮箱、发送内网 4.1：邮箱设置、邮箱查询 4.2：同意、查询
    isDel: isDel, //0：邮箱及同意书数据 1：操作数据
    operatorStatus: operatorStatus, //操作是否成功 1成功 0失败
    through: through, //操作失败的原因
    duration: time, //语音使用时间 秒
    timestamp: new Date().getTime() + "", //时间戳
  };
  data = JSON.stringify(data);
  let sign = sm3(data);
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  let addOperatorList;
  $.ajax({
    // url: localUrlLink + iscp_port + "/tjAiAssistant/operator/addOperator",
    url: localUrlLink + iscp_port + "/yipailu/operator/addOperator",
    type: "post",
    async: true, //是否同步，false表示同步请求 true表示异步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      sign: sign,
      Authentication: AuthenticationSession,
    },
    success: (res, txt, xhr) => {
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");
        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
          }
        } else if (res.code == 500) {
          // mui.toast(res.resultValue, {
          //     duration: 'long',
          //     type: 'div'
          // })
        } else {
          // mui.toast("请求异常请稍后再试", {
          //     duration: 'long',
          //     type: 'div'
          // })
        }
      } else {
        // mui.toast("sign验证失败", {
        //     duration: 'long',
        //     type: 'div'
        // })
      }
      addOperatorList = res;
      return addOperatorList;
    },
    error: (e) => {
      // mui.toast("请求异常请稍后再试", {
      //     duration: 'long',
      //     type: 'div'
      // })
    },
  });
  return addOperatorList;
}
/*操作日志同步接口，只适用于知情同意书,其他接口不使用*/
function securityAgreement(type, basic, content, isDel) {
  let userId = sessionStorage.getItem("userId");
  let unitId = sessionStorage.getItem("unitId");
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let data = {
    userId: userId, //用户id
    unitId: unitId, //单位id
    timestamp: new Date().getTime() + "", //时间戳
  };
  data = JSON.stringify(data);
  let sign = sm3(data);
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  let addOperatorList;
  $.ajax({
    // url: localUrlLink + iscp_port + "/tjAiAssistant/securityAgreement/add",
    url: localUrlLink + iscp_port + "/yipailu/securityAgreement/add",
    type: "post",
    async: false, //是否同步，false表示同步请求 true表示异步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      sign: sign,
      Authentication: AuthenticationSession,
    },
    success: (res, txt, xhr) => {
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");

        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
          }
        } else if (res.code == 500) {
          mui.toast(res.resultValue, {
            duration: "long",
            type: "div",
          });
        } else {
          mui.toast("请求异常请稍后再试", {
            duration: "long",
            type: "div",
          });
        }
        addOperatorList = res;
        return addOperatorList;
      }
    },
    error: (e) => {
      mui.toast("请求异常请稍后再试", {
        duration: "long",
        type: "div",
      });
    },
  });
  return addOperatorList;
}

// 验证邮箱
function validateMail(mail) {
  //校验邮箱
  var reg =
    /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
  let ismail = reg.test(mail);
  if (!ismail) {
    return false;
  } else {
    return true;
  }
}
/* 发送邮箱公共接口*/
function mailbox(
  messageTitle,
  sceneNo,
  fileName,
  fileExt,
  message,
  orgId,
  userId,
  userName,
  toMail,
  timestamp,
  temp,
  reportCode
) {
  console.log(message,563);
  console.log(orgId,564);
  console.log(messageTitle,565);
  console.log(reportCode,572);
  userId = sessionStorage.getItem("userId");
  orgId = sessionStorage.getItem("unitId");
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  // 注册邮箱发送验证码
  if (sceneNo != 41) {
    toMail = sessionStorage.getItem("toMail");
    let validateMailFlag = validateMail(toMail);
    // 发送邮箱前判断是否注册过
    if (!validateMailFlag) {
      $(".loader").css("display", "none");
      $(".curtain").css("display", "none");
      mui.toast("请前往‘我的’页面设置内网邮箱！", {
        duration: "long",
        type: "div",
      });
      return;
    }
  }
//   let msgString;
//   let newFileContent;
  //   if (sceneNo == 3 || sceneNo == 8) {
  //     msgString = fileContent + "," + sm3(fileContent);
  //     newFileContent = sm2.doEncrypt(
  //       msgString,
  //       sessionStorage.getItem("bpuk"),
  //       1
  //     );
  //   } else {
  //     newFileContent = fileContent;
  //   }
//   if (sceneNo == 3 || sceneNo == 8) {
//     msgString = message + "," + sm3(message);
//     newFileContent = sm2.doEncrypt(
//       msgString,
//       sessionStorage.getItem("bpuk"),
//       1
//     );
//   } else {
//     newFileContent = message;
//   }

  // userName = sm2UserName()
  // if (userName == "***") {
  //     alert("userName解密错误")
  //     return
  // }
  // let msgName = userName + "," + sm3(userName)
  // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
  let data = {
    messageTitle:messageTitle,
    // 1:打印文字识别 2:手写文字识别3:身份证识别 4:增值税专票识别 5:火车票识别 6:表格识别 7:Pdf转word 8:银行卡识别 9:增值税普票识别 10:工作票识别 11:操作票识别 12:出租车票识别 13:航空行程单识别 31:现场速记 32:语音笔记 33:录音转写
    // "sceneName": sceneName,//场景名称(身份证识别、增值税识别、火车票识别、手写文字识别、打印文字识别、pdf转word）
    sceneNo: sceneNo, //("1","打印文字识别"),("2", "手写文字识别"),("3", "身份证识别"),("4", "增值税专票识别"),("5", "火车票识别"),("6", "表格识别"),("7", "Pdf转word"),("8", "银行卡识别"),("9", "增值税普票识别"),
    //("10", "工作票识别"),("11", "操作票识别"),("12", "出租车票识别"),("13", "航空行程单识别"),("31", "现场速记"),("32", "语音笔记"),("33", "录音转写"),（"4,1", "我的"）
    fileName: fileName, //文本名称
    fileExt: fileExt, //文本后缀名称
    // message: newFileContent, //识别后内容
    message:message,
    orgId: orgId, //单位id
    userId: userId, //用户id
    userName: "", //用户名称
    toMail: toMail, //发送给谁 453707600@qq.com  15146764979@163.com
    // "toMail": toMail,//发送给谁
    timestamp: timestamp,
    reportCode:reportCode
  };
  console.log(data.message,635);
  console.log(data,632);
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  data = JSON.stringify(data);
  let sign = sm3(data);
  console.log(sign,612);
  let mailboxReturn;
  $.ajax({
    // url:
    //   localUrlLink +
    //   iscp_port +
    //   "/tjAiAssistant/IdentificationFile/fileDataAdd",
      url:
      localUrlLink +
      iscp_port +
      "/yipailu/IdentificationFile/fileDataAdd",
    type: "post",
    async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      sign: sign,
      Authentication: AuthenticationSession,
    },
    success: (res, txt, xhr) => {
      mailboxReturn = res.code;
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");

        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
            if (sceneNo == 41) {
              setTimeout(() => {
                $(".loader").css("display", "none");
                $(".curtain").css("display", "none");
                mui.toast("验证码已发送至内网邮箱", {
                  duration: "long",
                  type: "div",
                });
              }, 2000);
            } else {
              setTimeout(() => {
                $(".loader").css("display", "none");
                $(".curtain").css("display", "none");
                mui.toast("已发送成功", {
                  duration: "long",
                  type: "div",
                });
              }, 2000);
            }
          }
        } else if (res.code == 500) {
          $(".loader").css("display", "none");
          $(".curtain").css("display", "none");
          mui.toast(res.resultValue, {
            duration: "long",
            type: "div",
          });
        } else {
          $(".loader").css("display", "none");
          $(".curtain").css("display", "none");
          mui.toast("请求异常,请稍后再试", {
            duration: "long",
            type: "div",
          });
        }
      } else {
        $(".loader").css("display", "none");
        $(".curtain").css("display", "none");
      }
      return mailboxReturn;
    },
    error: (e) => {
      //  setTimeout(()=>{
      $(".loader").css("display", "none");
      $(".curtain").css("display", "none");
      mui.toast("请求异常,请稍后再试", {
        duration: "long",
        type: "div",
      });
      // },2000)
    },
  });
  return mailboxReturn;
}
// 语音笔记创建接口
function getaddVoice(messageTitle, message, saveType, timestamp, sceneNo) {
  userId = sessionStorage.getItem("userId");
  // userName = sm2UserName()
  // if (userName == "***") {
  //     alert("userName解密错误")
  //     return
  // }
  // let msgName = userName + "," + sm3(userName)
  // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
  orgId = sessionStorage.getItem("unitId");
  toMail = sessionStorage.getItem("toMail");
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let data = {
    sceneNo: sceneNo, //31:现场速记 32:语音笔记
    messageTitle: messageTitle, //笔记标题
    message: message, //笔记内容
    orgId: orgId, //单位id
    saveType: saveType, //1是完成按钮 0是发送邮箱按钮
    userId: userId, //用户id
    userName: "", //用户名称
    timestamp: timestamp,
    toMail: toMail, //发送给谁
  };
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  data = JSON.stringify(data);
  let sign = sm3(data);
  let getaddVoiceReturn;
  $.ajax({
    // url: localUrlLink + iscp_port + "/tjAiAssistant/voice/insertVoiceNotes",
    url: localUrlLink + iscp_port + "/yipailu/voice/insertVoiceNotes",
    type: "post",
    async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authentication: AuthenticationSession,
      sign: sign,
    },
    success: (res, txt, xhr) => {
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");
        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
            if (saveType == 1) {
              mui.toast("已保存", {
                duration: "long",
                type: "div",
              });
            } else if (saveType == 0) {
              mui.toast("已发送成功", {
                duration: "long",
                type: "div",
              });
            }
            if (sceneNo == 32 && saveType == 1) {
              setTimeout(() => {
                $(location).attr("href", "Voice.html");
              }, 1000);
            } else if (sceneNo == 31 && saveType == 1) {
              setTimeout(() => {
                $(location).attr("href", "OnSiteShorthand.html");
              }, 1000);
            }
          }
        } else if (res.code == 500) {
          mui.toast(res.resultValue, {
            duration: "long",
            type: "div",
          });
        } else {
          mui.toast("失败", {
            duration: "long",
            type: "div",
          });
        }
        getaddVoiceReturn = res;
        return getaddVoiceReturn;
      } else {
        mui.toast("完整性校验失败", {
          duration: "long",
          type: "div",
        });
      }
    },
    error: (e) => {
      mui.toast("请求异常,请稍后再试", {
        duration: "long",
        type: "div",
      });
    },
  });
  return getaddVoiceReturn;
}
// 语音笔记修改接口
function getreviseVoice(
  id,
  messageTitle,
  message,
  saveType,
  timestamp,
  sceneNo
) {
  userId = sessionStorage.getItem("userId");
  // userName = sm2UserName()
  // if (userName == "***") {
  //     alert("userName解密错误")
  //     return
  // }
  // let msgName = userName + "," + sm3(userName)
  // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
  toMail = sessionStorage.getItem("toMail");
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let data = {
    id: id, //主键id
    messageTitle: messageTitle, //笔记标题
    message: message, //笔记内容
    saveType: saveType, //1是完成按钮 0是发送邮箱按钮
    timestamp: timestamp,
    toMail: toMail, //发送给谁
    sceneNo: sceneNo,
  };
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  data = JSON.stringify(data);
  let sign = sm3(data);
  let getreviseVoiceReturn;
  $.ajax({
    // url: localUrlLink + iscp_port + "/tjAiAssistant/voice/updateVoiceNotes",yipailu
    url: localUrlLink + iscp_port + "/yipailu/voice/updateVoiceNotes",
    type: "post",
    async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authentication: AuthenticationSession,
      sign: sign,
    },
    success: (res, txt, xhr) => {
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");

        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
            mui.toast("已保存", {
              duration: "long",
              type: "div",
            });
            if (sceneNo == 32 && saveType == 1) {
              setTimeout(() => {
                $(location).attr("href", "Voice.html");
              }, 1000);
            } else if (sceneNo == 31 && saveType == 1) {
              setTimeout(() => {
                $(location).attr("href", "OnSiteShorthand.html");
              }, 1000);
            }
          }
        } else if (res.code == 500) {
          mui.toast(res.resultValue, {
            duration: "long",
            type: "div",
          });
        } else {
          mui.toast("失败", {
            duration: "long",
            type: "div",
          });
        }
      } else {
        mui.toast("完整性校验失败", {
          duration: "long",
          type: "div",
        });
      }
      getreviseVoiceReturn = res;
      return getreviseVoiceReturn;
    },
    error: (e) => {
      mui.toast("请求异常,请稍后再试", {
        duration: "long",
        type: "div",
      });
    },
  });
  return getreviseVoiceReturn;
}
// 语音列表接口
function shorthandListPost(sceneNo) {
  userId = sessionStorage.getItem("userId");
  // userName = sm2UserName()
  // if (userName == "***") {
  //     alert("userName解密错误")
  //     return
  // }
  // let msgName = userName + "," + sm3(userName)
  // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
  orgId = sessionStorage.getItem("unitId");
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let data = {
    orgId: orgId, //单位id
    userId: userId, //用户id
    sceneNo: sceneNo, //31:现场速记 32:语音笔记
    timestamp: new Date().getTime() + "",
  };
  data = JSON.stringify(data);
  let sign = sm3(data);

  let AuthenticationSession = sessionStorage.getItem("Authentication");
  var arr;
  $.ajax({
    // url: localUrlLink + iscp_port + "/tjAiAssistant/voice/queryVoiceNotes",yipailu
    url: localUrlLink + iscp_port + "/yipailu/voice/queryVoiceNotes",
    type: "post",
    async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authentication: AuthenticationSession,
      sign: sign,
    },
    success: (res, txt, xhr) => {
      let sm3res = JSON.stringify(res);
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");

        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
          }
        } else if (res.code == 500) {
          mui.toast(res.resultValue, {
            duration: "long",
            type: "div",
          });
        } else {
          mui.toast("请求异常,请稍后再试", {
            duration: "long",
            type: "div",
          });
        }
        arr = res;
        return arr;
      } else {
        mui.toast("完整性校验失败", {
          duration: "long",
          type: "div",
        });
      }
    },
    error: (e) => {
      mui.toast("请求异常,请稍后再试", {
        duration: "long",
        type: "div",
      });
    },
  });
  return arr;
}
// 语音删除功能
function shorthandDelete(id) {
  userId = sessionStorage.getItem("userId");
  // userName = sm2UserName()
  // if (userName == "***") {
  //     alert("userName解密错误")
  //     return
  // }
  // let msgName = userName + "," + sm3(userName)
  // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let data = {
    id: id, //单位id
    timestamp: new Date().getTime() + "",
  };
  data = JSON.stringify(data);
  let sign = sm3(data);
  let resResult;
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  $.ajax({
    // url: localUrlLink + iscp_port + "/tjAiAssistant/voice/deleteVoiceNotes",
    url: localUrlLink + iscp_port + "/yipailu/voice/deleteVoiceNotes",
    type: "post",
    async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authentication: AuthenticationSession,
      sign: sign,
    },
    success: (res, txt, xhr) => {
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");

        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
            mui.toast("已删除", {
              duration: "long",
              type: "div",
            });
          }
        } else if (res.code == 500) {
          mui.toast(res.resultValue, {
            duration: "long",
            type: "div",
          });
        } else {
          mui.toast("请求异常,请稍后再试", {
            duration: "long",
            type: "div",
          });
        }
        resResult = res.resultValue;
        return resResult;
      } else {
        mui.toast("完整性校验失败", {
          duration: "long",
          type: "div",
        });
      }
    },
    error: (e) => {
      mui.toast("请求异常,请稍后再试", {
        duration: "long",
        type: "div",
      });
    },
  });
  return resResult;
}

// 退出断开会话
function IscLogout() {
  userId = sessionStorage.getItem("userId");
  // userName = sm2UserName()
  // if (userName == "***") {
  //     alert("userName解密错误")
  //     return
  // }
  // let msgName = userName + "," + sm3(userName)
  // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let data = {
    userId: userId, //单位id
    timestamp: new Date().getTime() + "",
  };
  data = JSON.stringify(data);
  let sign = sm3(data);
  let resResult;
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  $.ajax({
    // url: localUrlLink + iscp_port + "/tjAiAssistant/isc/logout",
    url: localUrlLink + iscp_port + "/yipailu/isc/logout",
    type: "post",
    async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authentication: AuthenticationSession,
      sign: sign,
    },
    success: (res, txt, xhr) => {
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication");

        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
          }
        } else if (res.code == 500) {
          mui.toast(res.resultValue, {
            duration: "long",
            type: "div",
          });
        } else {
          mui.toast("请求异常请稍后再试", {
            duration: "long",
            type: "div",
          });
        }
        resResult = res;
        return resResult;
      } else {
        mui.toast("完整性校验失败", {
          duration: "long",
          type: "div",
        });
      }
    },
    error: (e) => {
      mui.toast("请求异常,请稍后再试", {
        duration: "long",
        type: "div",
      });
    },
  });
  return resResult;
}

/**
 * 获取当前积分 次数等信息
 * sceneNo 操作类型
 * time 使用次数 或者 使用秒数
 * 前端：根据时间段，分配次数，积分规则：
 * 0-200   5次ocr识别，语音识别10分钟。
 * 200-500  10次 ocr识别 语音20分钟。
 * 500-2000  20次ocr识别，语音40分钟。
 * 2000-5000  30次ocr识别，语音识别60分钟。
 * 5000-10000  50次 ocr识别 语音120分钟
 * 10000以上   80次 ocr识别  语音180分钟
 *
 * "operatorType": type, //type 1：用户登录注销 2：OCR识别 3：语音识别 4：我的
 * "operatorBasic": basic, //基于type 1.1：用户登录 1.2：用户注销 2.1：打印文字识别 2.2：手写文字识别 2.3：身份证识别 2.4：增值税专票识别 2.5：火车票识别 2.6：表格识别 2.7：Pdf转word 2.8：银行卡识别 2.9：增值税普票识别 2.10：工作票识别 2.11：操作票识别 2.12：出租车票识别 2.13：航空行程单识别 3.1：现场速记 3.2：语音笔记 3.3：录音转写 4.1：邮箱 4.2：安全知情同意书
 *
 * */
function Integral(operatorType, time) {
  time = Number(time);
  // 获取剩余ocr次数和剩余时间
  let integralTotal = JSON.parse(sessionStorage.getItem("integralTotal"));
  if (operatorType == 2) {
    // ocr
    integralTotal.ocr = integralTotal.ocr - time;
  } else if (operatorType == 3) {
    // 语音
    integralTotal.time = integralTotal.time - time;
    integralTotal.timeDivide = (integralTotal.time / 60).toFixed(0);
  } else if (operatorType == 5) {
    let integral = Number(sessionStorage.getItem("integral"));
    sessionStorage.setItem("integral", integral + time);
    // 加分后 更新ocr次数 语音识别时间
    integralTotal = ScoreLevel(
      integral,
      integralTotal.ocrInte - integralTotal.ocr,
      integralTotal.timeInte * 60 - integralTotal.time
    );
  }
  sessionStorage.setItem("integralTotal", JSON.stringify(integralTotal));
}

// 计算剩余 次数 时间 初始化
function ScoreLevel(integral, ocrFrequency, voiceTime) {
  // let integral = sessionStorage.getItem("integral");//登录后当前积分
  // let ocrFrequency = sessionStorage.getItem("ocrFrequency");//ocr已使用次数
  // let voiceTime = sessionStorage.getItem("voiceTime");//语音已使用时间
  // let upSampleFre = sessionStorage.getItem("upSampleFre");//当日上传样本次数
  // let upTotalSampleFre = sessionStorage.getItem("upTotalSampleFre");//累计上传样本次数
  // let integralRanking = sessionStorage.getItem("integralRanking");//积分排名
  let data;
  if (integral < 200) {
    return (data = {
      ocr: 5 - ocrFrequency,
      time: 600 - voiceTime,
      ocrInte: 5,
      timeInte: 10,
      timeDivide: ((600 - voiceTime) / 60).toFixed(0),
    });
  }
  if (integral < 500) {
    return (data = {
      ocr: 10 - ocrFrequency,
      time: 1200 - voiceTime,
      ocrInte: 10,
      timeInte: 20,
      timeDivide: ((1200 - voiceTime) / 60).toFixed(0),
    });
  }
  if (integral < 2000) {
    return (data = {
      ocr: 20 - ocrFrequency,
      time: 2400 - voiceTime,
      ocrInte: 20,
      timeInte: 40,
      timeDivide: ((2400 - voiceTime) / 60).toFixed(0),
    });
  }
  if (integral < 5000) {
    return (data = {
      ocr: 30 - ocrFrequency,
      time: 3600 - voiceTime,
      ocrInte: 30,
      timeInte: 60,
      timeDivide: ((3600 - voiceTime) / 60).toFixed(0),
    });
  }
  if (integral < 10000) {
    return (data = {
      ocr: 50 - ocrFrequency,
      time: 7200 - voiceTime,
      ocrInte: 50,
      timeInte: 120,
      timeDivide: ((7200 - voiceTime) / 60).toFixed(0),
    });
  }
  return (data = {
    ocr: 80 - ocrFrequency,
    time: 10800 - voiceTime,
    ocrInte: 80,
    timeInte: 180,
    timeDivide: ((10800 - voiceTime) / 60).toFixed(0),
  });
}

// 解密姓名
function sm2UserName() {
  let newUserName;
  let userNameString = sm2.doDecrypt(
    sessionStorage.getItem("userName"),
    sessionStorage.getItem("fprk"),
    1
  );
  let userNameList = userNameString.split(",");
  if (sm3(userNameList[0]) == userNameList[1]) {
    newUserName = userNameList[0];
    return newUserName;
  } else {
    return "***";
  }
}
// 手机号脱敏 11位手机号中间四位脱敏显示，例如：187****1234
function noPassByMobile(str) {
  if (null != str && str != undefined) {
    var pat = /(\d{3})\d*(\d{4})/;
    return str.replace(pat, "$1****$2");
  } else {
    return "";
  }
}

// 姓名脱敏
/**
 * 姓名脱敏处理，规则：3个字以内脱敏第一个字，4—6个字脱敏前两个字，大于6个字脱敏第3—6个字，示例：张三（三）、张三水（三水）、长孙无忌（**无忌）、罗斯托罗司机格（罗斯XXXX格）
 *
 *
 */
function noPassByName(str) {
  if (null != str && str != undefined) {
    if (str.length == 2) {
      return str.substring(0, 1) + "*"; //截取name 字符串截取第一个字符，
    } else if (str.length == 3) {
      return str.substring(0, 1) + "*" + str.substring(2, 3); //截取第一个和第三个字符
    } else if (str.length > 3) {
      return str.substring(0, 1) + "*" + "*" + str.substring(3, str.length); //截取第一个和大于第4个字符
    }
  } else {
    return "";
  }
}

// 身份证脱敏
function noPassIdCard(str) {
  if (!!str) {
    return str.replace(/(\w{4})\w*(\w{4})/, "$1********$2");
  } else {
    return "";
  }
}

// 银行卡脱敏
function noPassBankCard(str) {
  if (!!str && str.length > 8) {
    return `${str.substring(0, 4)} ${"*"
      .repeat(str.length - 8)
      .replace(/(.{4})/g, `$1 `)}${str.length % 4 ? " " : ""}${str.slice(-4)}`;
  } else {
    return "";
  }
}

// window.alert = alert;

// function alert(data) {

//     var a = document.createElement("div"),

//         p = document.createElement("p"),

//         btn = document.createElement("div"),

//         textNode = document.createTextNode(data ? data : ""),

//         btnText = document.createTextNode("确定");

//     // 控制样式

//     css(a, {

//         "position": "fixed",

//         "left": "0",

//         "right": "0",

//         "top": "20%",

//         "width": "20rem",

//         "margin": "0 auto",

//         "background-color": "#f00",

//         "font-size": "20px",

//         "text-align": "center"

//     });

//     css(btn, {

//         "background": "rgb(255, 255, 255)",
//         "color": "rgb(0,0,0)"

//     })

//     // 内部结构套入

//     p.appendChild(textNode);

//     btn.appendChild(btnText);

//     a.appendChild(p);

//     a.appendChild(btn);

//     // 整体显示到页面内

//     document.getElementsByTagName("body")[0].appendChild(a);

//     // 确定绑定点击事件删除标签

//     btn.onclick = function () {

//         a.parentNode.removeChild(a);

//     }

// }

// function css(targetObj, cssObj) {

//     var str = targetObj.getAttribute("style") ? targetObj.getAttribute("style") : "";

//     for (var i in cssObj) {

//         str += i + ":" + cssObj[i] + ";";

//     }

//     targetObj.style.cssText = str;
// }
